package ua.com.softway.mail;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;

import ua.com.softway.db.Persistence;

class TransactionControl {
    EntityTransaction transaction;
    EntityManager entityManager;
    
    public void begin() {
        if (transaction != null)
            commit();
        
        EntityManagerFactory entityManagerFactory = Persistence.getEntityManagerFactory();
        
        entityManager = entityManagerFactory.createEntityManager();
        Persistence.setCurrentEntityManager(entityManager);
        
        transaction = entityManager.getTransaction();
        transaction.begin();
    }
    
    public void commit() {
        entityManager.flush();
        transaction.commit();
        
        entityManager.close();
        Persistence.setCurrentEntityManager(null);
        
        transaction = null;
        entityManager = null;
    } 
}
